import crypto from 'crypto'
// 全局公共方法,不能使用箭头函数, 会找不到作用域this
export default {
  // 提示框
  alert(title, message) {
    return new Promise((resolve, reject) => {
      this.$msgbox.alert(this.$t(message),this.$t(title), {
        confirmButtonText: this.$t('确定')
      }).then(() => {
        resolve(true)
      }).catch(() => {
        resolve(false)
      });
    })
  },
  // 确认框
  confirm(title, message, type) {
    return new Promise((resolve, reject) => {
      if(!type) {
        type = 'info'
      }
      this.$msgbox.confirm(this.$t(message),this.$t(title), {
        confirmButtonClass: 'btn-custom-confirm',
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消')
      }).then(() => {
        resolve(true)
      }).catch(() => {
        resolve(false)
      });
    })
  },
  // 内容框
  prompt(title, message) {
    return new Promise((resolve, reject) => {
      this.$msgbox.prompt('', this.$t(title), {
        confirmButtonClass: 'btn-custom-confirm',
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        inputPlaceholder: this.$t(message)
      }).then(({ value }) => {
        resolve(value)
      }).catch(() => {
        resolve(false)
      });
    })
  },
  // 操作成功提醒（success）
  success(command) {
    let message = {
        add: '添加成功',
        upd: '修改成功',
        del: '删除成功',
        exa: '审核成功',
        ref: '刷新成功',
        set: '设置成功'
    }
    this.$message.success(command && message[command] || '操作成功')
    return true
  },
  // 操作失败提醒（faild）
  faild(command) {
      let message = {
          add: '添加失败',
          upd: '修改失败',
          del: '删除失败',
          exa: '审核失败',
          ref: '刷新失败',
          set: '设置失败'
      }
      this.$message.error(command && message[command] || '操作失败')
      return true
  },
  // 时间格式化
  dateFormat(fmt, date) {
    // eslint-disable-next-line no-unused-expressions
    if (typeof date === 'string') {
      date = new Date(date);
    }
    let ret;
    const opt = {
      'Y+': date.getFullYear().toString(), // 年
      'm+': (date.getMonth() + 1).toString(), // 月
      'd+': date.getDate().toString(), // 日
      'H+': date.getHours().toString(), // 时
      'M+': date.getMinutes().toString(), // 分
      'S+': date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp('(' + k + ')').exec(fmt);
      if (ret) {
        // eslint-disable-next-line eqeqeq
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
      }
    }
    return fmt;
  },
  // 模板制作时钟区格式转换
  changeTemplateClockFormat(val) {
    let html = ''
    let data = ''
    let time = ''
    let week = ''
    let week_zh = ''
    const now = new Date()
    switch(val) {
        case '1':
            data = this.$moment(now).format('HH:mm')
            html = `${data}`
            break
        case '2':
            data = this.$moment(now).format('HH:mm:ss')
            html = `${data}`
            break
        case '3':
            data = this.$moment(now).format('YYYY-MM-DD')
            html = `${data}`
            break
        case '4':
            data = this.$moment(now).format('YYYY-MM-DD HH:mm')
            html = `${data}`
            break
        case '5':
            data = this.$moment(now).format('YYYY-MM-DD')
            time = this.$moment(now).format('HH:mm')
            html = `${data}<br/>${time}`
            break
        case '6':
            data = this.$moment(now).format('YYYY-MM-DD')
            week = this.$moment(now).format('dddd')
            time = this.$moment(now).format('HH:mm:ss')
            html = `${data}<br/>${week}<br/>${time}`
            break
        case '7':
            data = this.$moment(now).format('YYYY-MM-DD')
            week = this.$moment(now).format('dddd')
            time = this.$moment(now).format('HH:mm:ss')
            html = `${time}<br/>${week}<br/>${data}`
            break
        case '8':
            data = this.$moment(now).format('YYYY年MM月DD日')
            week = this.$moment(now).format('dddd')
            week_zh = this.$formatTemplateClockWeek(week)
            html = `${data}(${week_zh})`
            break
        case '9':
            data = this.$moment(now).format('YYYY年MM月DD日')
            week = this.$moment(now).format('dddd')
            week_zh = this.$formatTemplateClockWeek(week)
            time = this.$moment(now).format('HH:mm')
            html = `${data}(${week_zh}) ${time}`
            break
        case '10':
            data = this.$moment(now).format('YYYY年MM月DD日')
            week = this.$moment(now).format('dddd')
            week_zh = this.$formatTemplateClockWeek(week)
            time = this.$moment(now).format('HH:mm:ss')
            html = `${data}<br/>${week_zh} ${time}`
            break
        case '11':
            data = this.$moment(now).format('YYYY年MM月DD日')
            week = this.$moment(now).format('dddd')
            time = this.$moment(now).format('HH:mm:ss')
            html = `${data}<br/>${week}<br/>${time}`
            break
        case '12':
            data = this.$moment(now).format('YYYY年MM月DD日')
            week = this.$moment(now).format('dddd')
            time = this.$moment(now).format('HH:mm:ss')
            html = `${time}<br/>${week}<br/>${data}`
            break
    }
    return html
  },
  formatTemplateClockWeek(val) {
    let result = ''
    switch(val) {
        case '星期一':
            result = '周一'
        break
        case '星期二':
            result = '周二'
        break
        case '星期三':
            result = '周三'
        break
        case '星期四':
            result = '周四'
        break
        case '星期五':
            result = '周五'
        break
        case '星期六':
            result = '周六'
        break
        case '星期日':
            result = '周日'
        break
    }
    return result
  },
  // 模板制作计时区格式转换
  /***
   * @type 计时类型
   * @val 要显示的格式类型
   * @endTime 结束时间
   */
  changeTemplateTimerFormat(type, val, endTime) {
    let html = ''
    let m1 = new Date()
    let m2 = this.$moment(endTime)
    let du = 0
    if(type === 'Countdown') {
      du = this.$moment.duration(m1 - m2 , 'ms')
    } else {
      du = this.$moment.duration(m2 - m1  , 'ms')
    }
    const days = du.get('days')
    const hours = du.get('hours')
    const mins = du.get('minutes')
    const ss = du.get('seconds')
    switch(val) {
      case "1":
        html = days
        break
      case "2":
        html = days + '天'
        break
      case "3":
        html = days + '天' + hours + '小时' + mins + '分'
        break
      case "4":
        html = days + '天' + hours + '小时' + mins + '分' + ss + '秒'
        break
    }
    return html
  },
  //查询用户操作权限
  checkOperationPermission(code){
    var result = false;
    var permissionStr = this.$store.getters.permissionlist;
    if (permissionStr === undefined || permissionStr === null || permissionStr.length === 0) {
      return false;
    }
    permissionStr.forEach(item => {
      if (item.code === code) {
        result = true;
        return result;
      }
    });
    return result;
  },
  //查询用户角色权限(导航栏)
  checkRolePermission(code){
    var result = false;
    var routes = this.$store.getters.role_permission;
    if (routes === undefined || routes === null || routes.length === 0) {
      return false;
    }
    routes.forEach(item => {
      if (item.code === code) {
        result = true;
        return result;
      }
    });
    return result;
  },


  // md5加密
  toMD5(data){
    var md5 = crypto.createHash('md5')
    md5.update(data) //需要加密的密码
    return md5.digest('hex') //password 加密完的密码
  },
  /**
   * This is just a simple version of deep copy
   * Has a lot of edge cases bug
   * If you want to use a perfect deep copy, use lodash's _.cloneDeep
   * @param {Object} source
   * @returns {Object}
   */
  deepClone(source) {
    if (!source && typeof source !== 'object') {
      throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = this.deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    })
    return targetObj
  }
}
